<?php

namespace app\admin\model;

use app\common\model\TimeModel;
use think\facade\Db;
use think\Model;

class UserOrder extends TimeModel
{

    protected $name = "user_order";

    protected $deleteTime = false;

    public function user()
    {
        return $this->belongsTo('app\admin\model\UserBase', 'uid', 'id');
    }

    public function store()
    {
        return $this->belongsTo('app\admin\model\ShopStore', 'store_id', 'id');
    }

    public function card()
    {
        return $this->belongsTo('\app\admin\model\CashcardUser', 'cashcard_id', 'id');
    }

    public static function onBeforeInsert(Model $model)
    {
        if ($model->create_time) {
            if (!is_int($model->create_time)) {
                $model->create_time = strtotime($model->create_time);
            }
        } else {
            $model->create_time = time();
        }
    }

    public static function onBeforeWrite(Model $model)
    {
        if ($model->update_time) {
            if (!is_int($model->update_time)) {
                $model->update_time = strtotime($model->update_time);
            }
        } else {
            $model->create_time = time();
        }
    }

    public static function onAfterRead(Model $model)
    {
        $model->pay_type_name = self::getPayType($model->pay_type);
        $model->status_name = self::getStatus($model->status, true);
        (isset($model->pay_time) && $model->pay_time > 0) && ($model->pay_at = date('Y-m-d H:i:s', $model->pay_time));
    }


    /**
     * 检测数据表是否存在
     * @param string $yearMonth
     * @return bool
     */
    public function detectTable(string $yearMonth = null)
    {
        $yearMonth ??= date('Ym');
        $prefix = config('database.connections.mysql.prefix');
        $check_sql = "show tables like '{$prefix}{$this->name}_{$yearMonth}';";
        $check = Db::query($check_sql);
        if (empty($check)) {
            $sql = $this->getCreateSql($yearMonth);
            $re = Db::execute($sql);
        }
        return true;
    }

    /**
     * 根据后缀获取创建表的sql
     * @param string $yearMonth
     * @return string
     */
    protected function getCreateSql(string $yearMonth)
    {
        $prefix = config('database.connections.mysql.prefix');
        return <<<EOT
        CREATE TABLE `{$prefix}{$this->name}_{$yearMonth}` (
            `id` int(10) unsigned NOT NULL COMMENT 'ID' Auto_Increment,
            `order_sn` varchar (50) NOT NULL DEFAULT '' COMMENT '订单编号',
            `pay_type` tinyint (4) unsigned NOT NULL DEFAULT 1 COMMENT '支付类型',
            `uid` int (11) unsigned NOT NULL DEFAULT 0 COMMENT '消费者id',
            `total_price`  float(10,2) NOT NULL DEFAULT 0.00 COMMENT '消费总额',
            `cashcard_id` int (11) unsigned DEFAULT 0 COMMENT '代金券id',
            `cashcard_dec` float(10,2) unsigned DEFAULT 0.00 COMMENT '代金券减免',
            `true_price` float(10,2) unsigned DEFAULT 0.00 COMMENT '实际支付',
            `refund` float(10,2) unsigned DEFAULT 0.00 COMMENT '退款金额',
            `create_time` int(11) NOT NULL COMMENT '创建时间',
            `update_time` int(11) DEFAULT NULL COMMENT '更新时间',
            `pay_time` int(11) DEFAULT NULL COMMENT '支付时间',
            `refund_time` int(11) DEFAULT NULL COMMENT '退款时间',
            `status` tinyint(4)NOT NULL DEFAULT 1 COMMENT '订单状态',
            `store_id` int (11) unsigned DEFAULT 0 COMMENT '店铺id',
            `terminal_id` int (11) unsigned DEFAULT 0 COMMENT '终端id',
            `inner_sn` varchar (50) NOT NULL DEFAULT '' COMMENT '内部订单编号',
            `epay_order_sn` varchar(50) DEFAULT '' COMMENT '金燕e付订单号',
            `query_times` int (11) unsigned NOT NULL DEFAULT 0 COMMENT '查询次数',
            `trans_date` varchar(20) DEFAULT '' COMMENT '订单生成日期',
            `actual_pay` float(10,2) unsigned DEFAULT 0.00 COMMENT '核算金额',
            PRIMARY KEY (`id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT COMMENT='订单表-{$yearMonth}';
        EOT;
    }

    /**
     * @title 分区插入
     * @param array $insert_data
     * @author FashionJune
     */
    public function insertApart(array $insert_data)
    {
        $create_time = is_int($insert_data['create_time']) ? $insert_data['create_time'] : strtotime($insert_data['create_time']);
        $yearMonth = date('Ym', $create_time ?? time());
        $this->detectTable($yearMonth);
        $this->setSuffix('_' . $yearMonth)->save($insert_data);
    }

    /**
     * @title 分区更新
     * @author FashionJune
     * @param array $update_data
     */
    public function updateApart(array $update_data)
    {
        $update_time = is_int($update_data['update_time']) ? $update_data['update_time'] : strtotime($update_data['update_time']);
        $yearMonth = date('Ym', $create_time ?? time());
        $this->detectTable($yearMonth);
        $this->setSuffix('_' . $yearMonth)->save($update_data);
    }



    /**
     * @title 获取支付类型
     * @param string $type
     * @param bool $color
     * @return string|array
     * @author FashionJune
     */
    public static function getPayType($type = 'all', $color = false)
    {
//        (1:支付宝,2:微信,3:银行卡)
        $type_arr = [1 => '支付宝', 2 => '微信', 3 => '银行卡'];
        $color_arr = [1 => '#1E9FFF', 2 => '#4bb368', 3 => '#f56c6c'];
        if ($type == 'all') {
            return $type_arr;
        } elseif ($color) {
            return ($type_arr[$type]) ? '<span style="color:' . $color_arr[$type] . '" >' . $type_arr[$type] . '</span>' : '';
        } else {
            return ($type_arr[$type]) ?? '';
        }
    }

    /**
     * @param string $status
     * @return string|string[]
     * @author FashionJune
     * @title 获取订单状态
     */
    public static function getStatus($status = 'all', $color = false)
    {
        $arr = [-1 => '支付失败', 1 => '待支付', 2 => '已支付', 3 => '退款中', 4 => '已退款'];
        $color_arr = [-1 => '#f56c6c', 1 => '#1E9FFF', 2 => '#4bb368', 3 => '#fc8621', 4 => '#333333'];
        if ($status === 'all') {
            return $arr;
        } elseif (isset($arr[$status])) {
            if ($color) {
                return '<span style="color: ' . $color_arr[$status] . '">' . $arr[$status] . '</span>';
            }
            return $arr[$status];
        } else {
            return '';
        }
    }

    /**
     * @title 生成订单编号
     * @param int $store_id
     * @param int $user_id
     * @param string $prefix
     * @return string
     * @throws \Exception
     * @author FashionJune
     */
    public function createOrderSn(int $store_id, int $user_id, $prefix = 'EP')
    {
        return $prefix . date('YmdHis') . random_int(100, 999);
//        return $prefix . $store_id . '_' . $user_id . date('YmdHis') . random_int(1000, 9999);
    }


    /**
     * @title 生成订单
     * @param int $store_id
     * @param int $uid
     * @param $total_price
     * @param $pay_info
     * @param array $card_info
     * @return bool
     * @throws \Exception
     * @author FashionJune
     */
    public function createOrderByUser(int $store_id, int $uid, $total_price, $pay_info, $card_info = [])
    {
        $insert_data = [
            'order_sn' => $pay_info['MerSeqNbr'],
            'pay_type' => $pay_info['pay_type'],
            'store_id' => $store_id,
            'uid' => $uid,
            'total_price' => $total_price,
            'cashcard_id' => $card_info['id'] ?? 0,
            'cashcard_dec' => $card_info['cate']['cashcard_price'] ?? 0,
//            'pay_time' => time(),
            'status' => 1,
            'inner_sn' => $pay_info['InnerFundTransNbr'],
        ];
        $insert_data['true_price'] = $insert_data['total_price'] - $insert_data['cashcard_dec'];
        $re = $this->save($insert_data);
//        $this->detectTable();
//        $re = $this->setSuffix('_' . date('Ym'))->save($insert_data);
        return true;
    }

    /**
     * @title 全额退款后更新订单状态
     * @param int $order_id
     * @author FashionJune
     */
    public function afterRefund(int $order_id)
    {
        $update_data = [
            'refund_time' => time(),
            'status' => 4
        ];
        $this->where('id', $order_id)->save($update_data);
    }


}